#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>

void Write(int wfd)
{
    int count = 0;
    char buffer[1024];
    while (true)
    {
        snprintf(buffer, sizeof(buffer), "child process write_%d\n", count++);
        write(wfd, buffer, strlen(buffer));
        sleep(1);
    }
}

void Read(int rfd)
{
    char buffer[1024];
    while(true)
    {
        int n = read(rfd,buffer,sizeof(buffer) - 1);
        if(n  > 0)
        {
        buffer[n] = 0;
        std::cout<< "father process read child process : " << buffer;
        }
    }
}

int main()
{
    int fds[2] = {0};
    int ret = pipe(fds);
    if (-1 == ret)
    {
        // 失败返回
        std::cerr << "pipe fail" << std::endl;
        return 1;
    }
    for(auto e : fds)
    {
        std::cout << "pipe fds : " << e << std::endl;
    }
    int pid = fork();
    if (pid == 0)
    {
        close(fds[0]);
        Write(fds[1]);

        close(fds[1]);
        exit(0);
    }
    close(fds[1]);
    Read(fds[0]);
 

    waitpid(pid, nullptr, 0);
    close(fds[0]);

    return 0;
}